package com.zhu.service.smtp.service.mail;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.zhu.service.base.config.MailConstance;

import com.zhu.service.smtp.pojo.Mail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class MailConsumer {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = MailConstance.MAIL_QUEUE_NAME)
    public void  handler(Message message, Channel channel) {

        Mail mail = (Mail) message.getPayload();
        String key="register_"+mail.getEmail();
        String code = mail.getCode();
        log.info("mail:============={}", mail.toString());
        MessageHeaders headers = message.getHeaders();
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG); //得到消息序号
        String msgId = (String) headers.get("spring_returned_message_correlation");
        Object o = redisTemplate.opsForValue().get(key);
        try {
            if (o!=null) {
                log.info("消息被消费======>{}", msgId);
                channel.basicAck(tag, false);
                return;
            }
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(mail.getEmail());
            helper.setSubject("欢迎注册");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("code", mail.getCode());
            String mails = templateEngine.process("mail", context);
            helper.setText(mails, true);
            javaMailSender.send(msg);
            log.info("邮件发送成功！");
            //将消息id存入redis

//            valueOperations.set("register_mail",mail.getCode());
            redisTemplate.opsForValue().set(key, code,10,TimeUnit.MINUTES);
//            redisTemplate.expire(key,20,TimeUnit.MINUTES);
            //手动确认消息
            channel.basicAck(tag, false);
        } catch (Exception e) {
            try {
                channel.basicNack(tag, false, true);
            } catch (IOException ioException) {
                log.error("邮件发送失败========={}", e.getMessage());
            }

            log.error("邮件发送失败========={}", e.getMessage());


        }

    }
}
